﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MaxLeaf.DB;
using MaxLeaf.Common;

namespace MaxLeaf.DAL.K2K
{
    /// <summary>
    /// 计量单位
    /// </summary>
    public class t_MeasureUnitDAL : BaseDAL
    {
        /*
         * exec sp_executesql N'INSERT INTO t_MeasureUnit (FName,FNumber,FAuxClass,FCoefficient,FConversation,FNameEn,FNameEnPlu,FMeasureUnitID,FPrecision,FShortNumber,FParentID) VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11)',N'@P1 varchar(80),@P2 varchar(30),@P3 varchar(8),@P4 float,@P5 int,@P6 varchar(255),@P7 varchar(255),@P8 int,@P9 int,@P10 varchar(80),@P11 int'
         * ,'testunit','testunit',' ',1,1,NULL,NULL,9082,0,'testunit',9082
         * 
         * exec sp_executesql N'Insert Into t_Item(FitemID,FItemClassID,FDetail,FLevel,FParentID,FNumber,FName,FShortNumber,FFullNumber,FDeleted) 
         * Values(9083,7,1,2,9082,@P1,@P2,@P3,@P4,@P5)',N'@P1 varchar(80),@P2 varchar(80),@P3 varchar(80),@P4 varchar(80),@P5 int'
         * ,'testunit','testunit','testunit','testunit',0
         */
        public t_MeasureUnitDAL()
            : base()
        {
            strTableName = "t_MeasureUnit";

            strDestRealKeyFieldName = "FName";
            strFieldNames = "FName,FNumber,FAuxClass,FCoefficient,FConversation,FNameEn,FNameEnPlu,FPrecision,FShortNumber,FParentID,FStandard";
        }
        string _strFParentID = null;
        public string GetFMeasureUnitID(DB.DBAccess dbOrgK3Con, DB.DBAccess dbDestK3Con, string strOrgFMeasureUnitID, string strFParentID)
        {
            string strDestKeyValue = UpdateMeasureUnit(dbOrgK3Con, dbDestK3Con, strOrgFMeasureUnitID, strFParentID);

            SaveKeyMap(dbDestK3Con, strOrgFMeasureUnitID, strDestKeyValue);

            return strDestKeyValue;
        }
        private string UpdateMeasureUnit(DB.DBAccess dbOrgK3Con, DB.DBAccess dbDestK3Con, string strOrgFMeasureUnitID, string strFParentID)
        {
            _strFParentID = strFParentID;

            string strSql =string.Empty;
            if (strOrgFMeasureUnitID.Equals("0") || strOrgFMeasureUnitID.Length == 0)
            {
                return string.Empty;
            }
            DataRow drOrgData = dbOrgK3Con.GetTableDataFirstRow(strTableName, new Dictionary<string, object>(){
                     { "FMeasureUnitID", strOrgFMeasureUnitID }
                 }
           );

            dictOtherKeyFieldsCond = new Dictionary<string, object>() { 
                    {"FParentID",drOrgData["FParentID"]}
                };
            dictDestOtherKeyFieldsCond = new Dictionary<string, object>() { 
                    {"FParentID",strFParentID}
                };

            string strDestFMeasureUnitID = GetDestFMeasureUnitID(dbOrgK3Con, dbDestK3Con, strOrgFMeasureUnitID);
            DataTable dtData = dbDestK3Con.GetTableData(strTableName, new Dictionary<string, object>() { { "FMeasureUnitID",strDestFMeasureUnitID }, { "FParentID", _strFParentID } });
            if (dtData.Rows.Count == 0)
            {
                dtData = dbDestK3Con.GetTableData(strTableName, new Dictionary<string, object>() { { "FName", drOrgData["FName"] }, { "FParentID", _strFParentID } });
            }
            if (dtData.Rows.Count > 0)
            {
                strSql = @"update t_MeasureUnit 
                    set FName=@FName
                    ,FNumber=@FNumber
                    ,FAuxClass=@FAuxClass
                    ,FCoefficient=@FCoefficient
                    ,FConversation=@FConversation
                    ,FNameEn=@FNameEn
                    ,FNameEnPlu=@FNameEnPlu
                    
                    ,FPrecision=@FPrecision
                    ,FShortNumber=@FShortNumber
                    ,FParentID=@FParentID
                    ,FStandard=@FStandard
                    ,funitgroupid=@FParentID
                    where FMeasureUnitID=@FMeasureUnitID
                ";
                KeyValuePair<string, IDataParameter[]> kvpUpdate = dbDestK3Con.CreateCondParam(new Dictionary<string, object>(){
                {"FName",drOrgData["FName"]}
                ,{"FNumber",
                     CvtFunc.ToString(drOrgData["FNumber"]).Equals(CvtFunc.ToString( dtData.Rows[0]["FNumber"]), StringComparison.InvariantCultureIgnoreCase )
                     ?CvtFunc.ToString( dtData.Rows[0]["FNumber"])
                     :GetNewFNumber(dbDestK3Con, CvtFunc.ToString(drOrgData["FNumber"]))
                     }
                ,{"FAuxClass",drOrgData["FAuxClass"]}
                ,{"FCoefficient",drOrgData["FCoefficient"]}
                ,{"FConversation",drOrgData["FConversation"]}
                ,{"FNameEn",drOrgData["FNameEn"]}
                ,{"FNameEnPlu",drOrgData["FNameEnPlu"]}
                
                ,{"FPrecision",drOrgData["FPrecision"]}
                ,{"FShortNumber",drOrgData["FShortNumber"]}
                ,{"FParentID",_strFParentID}    
             ,{"FStandard",drOrgData["FStandard"]}
                ,{"FMeasureUnitID",dtData.Rows[0]["FMeasureUnitID"]}
                
            });
                dbDestK3Con.ExecuteSql(strSql, kvpUpdate.Value);

                return CvtFunc.ToString(dtData.Rows[0]["FMeasureUnitID"]);
            }


            //fnumber必须唯一，但是实际用的是FName
            string strNewFNumber = GetNewFNumber(dbDestK3Con, CvtFunc.ToString(drOrgData["FNumber"]));
            string strFitemId = "-1";// GetFItemID(dbOrgCon, dbDestCon, CvtFunc.ToString(drOrgData["FParentID"]), _strFParentID, CvtFunc.ToString(drOrgData["FNumber"]));
            strSql = @"INSERT INTO t_MeasureUnit (funitgroupid,FName,FNumber,FAuxClass,FCoefficient,FConversation,FNameEn,FNameEnPlu,FPrecision,FShortNumber,FParentID,FStandard)
                values(@funitgroupid,@FName,@FNumber,@FAuxClass,@FCoefficient,@FConversation,@FNameEn,@FNameEnPlu,@FPrecision,@FShortNumber,@FParentID,@FStandard)";
            KeyValuePair<string, IDataParameter[]> kvpAdd = dbDestK3Con.CreateCondParam(new Dictionary<string, object>(){
                {"funitgroupid",_strFParentID}     
                ,{"FName",drOrgData["FName"]}
                ,{"FNumber",strNewFNumber}
                ,{"FAuxClass",drOrgData["FAuxClass"]}
                ,{"FCoefficient",drOrgData["FCoefficient"]}
                ,{"FConversation",drOrgData["FConversation"]}
                ,{"FNameEn",drOrgData["FNameEn"]}
                ,{"FNameEnPlu",drOrgData["FNameEnPlu"]}
                ,{"FMeasureUnitID",strFitemId}
                ,{"FPrecision",drOrgData["FPrecision"]}
                ,{"FShortNumber",strNewFNumber}
                ,{"FParentID",_strFParentID}  
                ,{"FStandard",drOrgData["FStandard"]}
                ,{"FitemID",strFitemId}
            });
            dbDestK3Con.ExecuteSql(strSql, kvpAdd.Value);


            //触发器得到FitemID
            DataRow drData = dbDestK3Con.GetTableDataFirstRow(strTableName, new Dictionary<string, object>() { { "FUnitGroupID", _strFParentID }, { "FName", drOrgData["FName"] } }, "FMeasureUnitID,FNumber,FName");


            strSql = string.Format(@"
                
                Insert Into t_Item(FitemID,FItemClassID,FDetail,FLevel,FParentID,FNumber,FName,FShortNumber,FFullNumber,FDeleted) 
                values({0},{1},{2},{3},{4},@FNumber,@FName,@FShortNumber,@FFullNumber,@FDeleted) 
                "
                , CvtFunc.ToInt(drData["FMeasureUnitID"])
                , 7
                , 1
                , 2
                , _strFParentID
                );
            KeyValuePair<string, IDataParameter[]> kvpItem = dbDestK3Con.CreateCondParam(new Dictionary<string, object>(){
                //{"FitemID",drData["FitemID"]}
                //,{"FItemClassID",7}
                //,{"FDetail","1"}
                //,{"FLevel","2"}
                //,{"FParentID",_strFParentID}
                {"FNumber",drData["FNumber"]}
                ,{"FName",drData["FName"]}
                ,{"FShortNumber",GetShortNumber(CvtFunc.ToString( drData["FNumber"]))}
                ,{"FFullNumber",drData["FNumber"]}
                ,{"FDeleted","0"}
            });
            dbDestK3Con.ExecuteSql(strSql, kvpItem.Value);
           


            return CvtFunc.ToString(drData["FMeasureUnitID"]);
        }

        private string GetDestFMeasureUnitID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgKeyValue)
        {
            if (dbDestK3Con.ServerMasterDB)
            {
                //如果是主帐套，就是原始值
                return strOrgKeyValue;
            }
            KeyValuePair<string, IDataParameter[]> kvp = dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "TableName", "t_Item" }, { "OrgKeyValue", strOrgKeyValue } });
            string strSql = string.Format("select DestKeyValue from mkeymap where {0}", kvp.Key);

            string strDestMapKeyValue = dbDestK3Con.GetValue(strSql, kvp.Value);
            if (strDestMapKeyValue.Length > 0)
            {
                return strDestMapKeyValue;
            }

            return "-1000";

        }

        
        private string GetNewFNumber(DBAccess dbDestK3Con, string strOrgFnumber)
        {
            string strSql = "select fnumber from t_MeasureUnit  where fnumber=@Fnumber ";
            KeyValuePair<string, IDataParameter[]> kvp = dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { {"fnumber",strOrgFnumber}});
            if (dbDestK3Con.GetDataFirstRow(strSql, kvp.Value) == null)
            {
                return strOrgFnumber;
            }

            int intFnumber = 1;
            if (BaseFunctions.IsNumeric(strOrgFnumber))
            {
                intFnumber = CvtFunc.ToInt(strOrgFnumber) + 1;
            }

            strSql = "select fnumber from t_MeasureUnit  where fnumber=@Fnumber ";
            kvp = dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "fnumber", intFnumber.ToString() } });
            while (dbDestK3Con.GetDataFirstRow(strSql, kvp.Value) != null)
            {
                intFnumber++;
                kvp = dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "fnumber", intFnumber.ToString() } });
            }
            return intFnumber.ToString();
        }

        private string GetFItemID(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgFParentID, string strFParentID, string strFnumber)
        {
            const string strFItemClassID = "7";
            const int intFDetail = 1;
            string strFItemId = string.Empty;
            t_ItemDAL dal = new t_ItemDAL(strFItemClassID, strUpdateFNumberTableName);


            strFItemId = dal.GetFItemId(dbOrgK3Con, dbDestK3Con, 2, strOrgFParentID, strFParentID, strFnumber, intFDetail);




            return strFItemId;
        }

        public override int Update(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strKeyValue)
        {
            KeyValuePair<string, IDataParameter[]> kvp = dbOrgK3Con.CreateCondParam(new Dictionary<string, object>() { {"FMeasureUnitID",strKeyValue }});
            string strOrgFParentID = dbOrgK3Con.GetValue(string.Format("select FParentID from t_MeasureUnit where {0} ", kvp.Key), kvp.Value);
            string strFParentID = new t_UnitGroupDAL().GetFUnitGroupID(dbOrgK3Con, dbDestK3Con, strOrgFParentID);
            int intUnitID= CvtFunc.ToInt( GetFMeasureUnitID(dbOrgK3Con, dbDestK3Con, strKeyValue, strFParentID));

            UpdateDefaultUnitID(dbDestK3Con);
            return intUnitID;
        }

        private void UpdateDefaultUnitID(DBAccess dbDestK3Con)
        {
            string strsql = "update t_UnitGroup set FDefaultUnitID=a.FMeasureUnitID  from t_MeasureUnit a  where a.FUnitGroupID=t_UnitGroup.FUnitGroupID and t_UnitGroup.FDefaultUnitID=0 and a.fstandard=1";
            dbDestK3Con.ExecuteSql(strsql);
        }

        public override string GetDestMapKeyValue(DBAccess dbOrgK3Con, DBAccess dbDestK3Con, string strOrgKeyValue)
        {
            if (dbDestK3Con.ServerMasterDB)
            {
                return strOrgKeyValue;
            }

            if (strOrgKeyValue.Equals("0"))
            {
                return "0";
            }
            return base.GetDestMapKeyValue(dbOrgK3Con, dbDestK3Con, strOrgKeyValue);
        }
    }
}
